<?php
class Admin_news extends Admin_Controller{
	function __construct(){
		parent :: __construct();
		$this->load->model("News_m");
		
		$this->_data['sidebar'] = "news";
		
		
 
	}
	
	function index(){
		$this->actualite();
		
	}
	
	function actualite(){
		is_admin();
		$this->session->set_userdata("type", "actualite");
		$this->_data['page_title'] ="Liste Actualite";
		$perpage = $this->uri->segment(3);
		$offset = $this->uri->segment(4);
		if($perpage == ""){
			$perpage = 10;
		}
		if($offset == ""){
			$offset = "";
		}
		$config['base_url'] = base_url()."index.php/admin_news/actualite/".$perpage."/";
		$config['per_page'] = $perpage;
		$config['uri_segment'] = 4;
		$config['total_rows'] = $this->News_m->count_news();
		if($offset > 0 && $offset == $config['total_rows']){
			$offset = $offset - $perpage;
		}
	
		$this->pagination->initialize($config); 
		$this->_data['pagination'] = $this->pagination->create_links();
		
		$q_list_news = $this->News_m->list_news("actualite", $perpage, $offset);
		
		$news = array();
		foreach($q_list_news as $key=>$value){
			$news[$key] = $value;
			$active_status = "Active";
			if($value['active'] != 1){
				$active_status = "Non-Active";
			}
			$post_time = date('d/m/Y h:i A', $value['post_time']);
			$description = character_limiter($value['description'], 40);
			$news[$key]['description'] = trim($description);
			$news[$key]['active'] = $active_status;
			$news[$key]['post_time'] = $post_time;
					
		}
		
		
		$this->_data['news_data'] = $news;
		
		$this->display_admin("admin/news/list_news");
	}
	
	function communique(){
		is_admin();
		$this->session->set_userdata("type", "communique");
		$this->_data['page_title'] ="Liste Communique";
		$perpage = $this->uri->segment(3);
		$offset = $this->uri->segment(4);
		if($perpage == ""){
			$perpage = 10;
		}
		if($offset == ""){
			$offset = "";
		}
		$config['base_url'] = base_url()."index.php/admin_news/communique/".$perpage."/";
		$config['per_page'] = $perpage;
		$config['uri_segment'] = 4;
		$config['total_rows'] = $this->News_m->count_communique();
		if($offset > 0 && $offset == $config['total_rows']){
			$offset = $offset - $perpage;
		}
	
		$this->pagination->initialize($config); 
		$this->_data['pagination'] = $this->pagination->create_links();
		
		$q_list_news = $this->News_m->list_news("communique", $perpage, $offset);
		
		$news = array();
		foreach($q_list_news as $key=>$value){
			$news[$key] = $value;
			$active_status = "Active";
			if($value['active'] != 1){
				$active_status = "Non-Active";
			}
			$post_time = date('d/m/Y h:i A', $value['post_time']);
			$description = character_limiter($value['description'], 40);
			$news[$key]['description'] = trim($description);
			$news[$key]['active'] = $active_status;
			$news[$key]['post_time'] = $post_time;
					
		}
		
		
		$this->_data['news_data'] = $news;
		
		$this->display_admin("admin/news/list_communique");
	}
	
	//-- add news --//
	function ajouter_actualite_communique(){
		is_admin();
		$this->_data['page_title'] = "Ajouter actualite";
		$this->_data['dd_companies'] = $this->News_m->_get_dd_company();
		$config = array(
							array("field" => "title",
							      "label" => lang("title"),
								  "rules" => "required|trim|xss_clean"
							      ),
							
							array("field" => "description",
							      "label" => lang("description"),
								  "rules" => "trim|xss_clean"
							      ),
							 
							array("field" => "content",
							      "label" => lang("content"),
								  "rules" => "required|trim|xss_clean"
							      ),
							      
							array("field" => "company",
							      "label" => lang("company"),
								  "rules" => "xss_clean|callback__check_dropdown"
							      ),
							
							array("field" => "type",
							      "label" => "Type",
								  "rules" => "xss_clean|callback__check_dropdown"
							      )

						);
		$this->form_validation->set_rules($config);//set validation rules
		
		if($this->input->post("submit")){
			
			if($this->form_validation->run()){
				/* if user select file upload $_FILES != null 
				 * $_FILES !=null check upload error and do upload
				 * $_FILES == null process form without upload image */
				                                                      
				if($_FILES['userfile']['tmp_name'] != null){
						$upload = $this->do_upload();
					
						if(isset($upload['error']) && ($upload['error']!=null)){
							 $this->_data['upload_error'] = $upload['error'];
							 $this->display_admin("admin/news/add_news");
						}else{
							$img_name = $upload['upload_data']['file_name'];
							$addtion_data = array("image" => $img_name,
												  "post_time" => now(),
												  "user_post" => $this->session->userdata("user_id"),
												  "active"    => 1,
												  "type"      => $this->input->post("type")						
												 );
							$query_insert_news = $this->News_m->ajouter_actualite($addtion_data);
							if($query_insert_news == TRUE){
								$this->session->set_flashdata("error", lang("add")." ".lang("success"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}else{
								$this->session->set_flashdata("error", lang("add")." ".lang("fail"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}
							
						}	
				}else{
							$addtion_data = array(
												  "image"     => null,
												  "post_time" => now(),
												  "user_post" => $this->session->userdata("user_id"),
												  "active"    => 1						
												 );
							$query_insert_news = $this->News_m->ajouter_actualite($addtion_data);
							if($query_insert_news == TRUE){
								$this->session->set_flashdata("error", lang("add")." ".lang("success"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}else{
								$this->session->set_flashdata("error", lang("add")." ".lang("fail"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}		
				}
				
			
			}else{
				$this->display_admin("admin/news/add_news");	
			}	
		}else{
			$this->display_admin("admin/news/add_news");	
		}
	}
	
	//--Edit News details--//
	function modifier_actualite($id=null){
		is_admin();
		if(!isset($id) || ($id == null)){
			redirect("Admin_news");
		}else{
			if($this->News_m->_get_news_details($id) === FALSE){
				redirect("Admin_news");	
			}
		}
		
		$this->_data['page_title'] = "Modifier actualite";
		$nd_row = $this->_load_actualite_details($id);
		$this->_data['id'] = $id;
	$config = array(
							array("field" => "title",
							      "label" => lang("title"),
								  "rules" => "required|trim|xss_clean"
							      ),
							
							array("field" => "description",
							      "label" => lang("description"),
								  "rules" => "trim|xss_clean"
							      ),
							 
							array("field" => "content",
							      "label" => lang("content"),
								  "rules" => "required|trim|xss_clean"
							      ),
							      
							array("field" => "company",
							      "label" => lang("company"),
								  "rules" => "xss_clean"
							      ),
							array("field" => "active",
							      "label" => lang("active"),
								  "rules" => "xss_clean"
							      ),
							array("field" => "type",
							      "label" => "type",
								  "rules" => "xss_clean"
							      ),

						);
		$this->form_validation->set_rules($config);//set validation rules
		
		if($this->input->post("submit")){
			
			if($this->form_validation->run()){
				/* if user select file upload $_FILES != null 
				 * $_FILES !=null check upload error and do upload
				 * $_FILES == null process form without upload image */
				                                                      
				if($_FILES['userfile']['tmp_name'] != null){
						$upload = $this->do_upload();
						
						if(isset($upload['error']) && ($upload['error']!=null)){
							 $this->_data['upload_error'] = $upload['error'];
							 $this->display_admin("admin/news/edit_news");
						}else{
							$image_to_delete = './assets/news_img/' . $nd_row->image;
                            $thumb_to_delete = './assets/news_img/thumbs/' . $nd_row->image;
                            delete_images($image_to_delete, $thumb_to_delete);
							$img_name = $upload['upload_data']['file_name'];
							$addtion_data = array("image" => $img_name,
												  "post_time" => now(),
												  "active"    => $this->input->post("active"),
												  "type"      => $this->input->post("type")						
												 );
								$query_update_news = $this->News_m->modifier_actualite($id, $addtion_data);
							if($query_update_news == TRUE){
								$this->session->set_flashdata("error", lang("edit_profile")." ".lang("success"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}else{
								$this->session->set_flashdata("error", lang("edit_profile")." ".lang("fail"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}		
							
						}	
				}else{
							$addtion_data = array(
												  "image"     =>$nd_row->image,
												  "post_time" => now(),
												  "active"    => $this->input->post("active"),
												  "type"      => $this->input->post("type")							
												 );
							$query_update_news = $this->News_m->modifier_actualite($id, $addtion_data);
							if($query_update_news == TRUE){
								$this->session->set_flashdata("error", lang("edit_profile")." ".lang("success"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}else{
								$this->session->set_flashdata("error", lang("edit_profile")." ".lang("fail"));
								if($this->input->post('type') == "actualite"){
									redirect("Admin_news");
								}elseif($this->input->post('type') == "communique"){
									redirect("Admin_news/communique");
								}
							}		
				}
				
			
			}else{
				$this->display_admin("admin/news/edit_news");	
			}	
		}else{
			$this->display_admin("admin/news/edit_news");	
		}
		
	}
	
	//--delete news--//
	function supprimer_actualite($id){
		is_admin();
		if(!isset($id) || ($id == null)){
				redirect("Admin_news");
			}else{
				if($this->News_m->_get_news_details($id) === FALSE){
					redirect("Admin_news");	
				}
		}
		$nd_row = $this->News_m->_get_news_details($id)->row();
		$query_delete_news = $this->News_m->delete_news($id);
		if($query_delete_news == TRUE){
				$image_to_delete = './assets/news_img/' . $nd_row->image;
                $thumb_to_delete = './assets/news_img/thumbs/' . $nd_row->image;
                delete_images($image_to_delete, $thumb_to_delete);
				$this->session->set_flashdata("error", lang("delete")." ".lang("success"));
				if($nd_row->type == "actualite"){
					redirect("Admin_news");
				}elseif($nd_row->type == "communique"){
					redirect("Admin_news/communique");
				}
		}else{
				$this->session->set_flashdata("error", lang("delete")." ".lang("fail"));
				if($nd_row->type == "actualite"){
					redirect("Admin_news");
				}elseif($nd_row->type == "communique"){
					redirect("Admin_news/communique");
				}
		}		
	
	}
	
	//--delete multi news--//
	function delete_multi_news(){
		is_admin();
        $list = "";
        $adelete = $this->input->post('delete');
        $N = count($adelete);
        for ($i = 0; $i < $N; $i++) {
            
         	$image = $this->News_m->_get_news_details($adelete[$i])->row();
                $image_to_delete = './assets/news_img/' . $image->image;
                $thumb_to_delete = './assets/news_img/thumbs/' . $image->image;
                if ($image->image != null) {
                    delete_images($image_to_delete, $thumb_to_delete);
                }
            
            if ($adelete[$i] != "")
                $list = $list . ',' . $adelete[$i];
        }
        $list = '(' . substr($list, 1) . ')';

        $query = $this->News_m->delete_multi_news($list);
        if ($query)
            $this->session->set_flashdata('error', lang('delete').' ' . lang('success'));
        else
            $this->session->set_flashdata('error', lang('delete').' ' . lang('fail'));
        if($this->session->userdata("type") == "actualite"){
        	redirect("Admin_news");	
        }elseif($this->session->userdata("type") == "communique"){
        	redirect("Admin_news/communique");
        }
        
	}
	
	/* upload photo */
	function do_upload(){
		$config = array('upload_path'   => './assets/news_img/',
					    'allowed_types' => 'gif|jpg|jpeg|png',
						'max_size'      => '5000',
						'max_width'     => '1024',
						'max_height'    => '768',
						'encrypt_name'  => 'TRUE'
		 	            );
		$this->load->library("upload", $config);
		
		if(!$this->upload->do_upload()){
			return $error = array('error' => $this->upload->display_errors());
		}else{
			$image_data = $this->upload->data();
			$config = array(
      						  'source_image' => $image_data['full_path'], //get original image
						      'new_image' => $image_data['file_path'] . 'thumbs', //save as new image //need to create thumbs first
						      'maintain_ratio' => true,
						      'width' => 150,
						      'height' => 100
 
   							 );
   			$this->load->library('image_lib', $config); //load library
    		$this->image_lib->resize(); //do whatever specified in config
			return $data = array('upload_data' => $this->upload->data());
		}
	}
	
	//--Load news detail--//
	function _load_actualite_details($id){
		$query_news_details = $this->News_m->_get_news_details($id);
		$nd_row = $query_news_details->row();
		$this->_data['title']       =  $title       = $nd_row -> title;
		$this->_data['description'] =  $description = $nd_row -> description;
		$this->_data['content']     =  $content     = $nd_row -> content;
		$this->_data['user_post']   =  $user_post   = $nd_row -> user_name;
		$this->_data['active']      =  $active   	= $nd_row -> active;
		$this->_data['company']     =  $company     = $nd_row -> company;
		$this->_data['type']        =  $type        = $nd_row -> type;
		$this->_data['dd_companies'] = $this->News_m->_get_dd_company(TRUE);
		
		$image = $nd_row->image;
		
		if($image != null){
			$file_path = "./assets/news_img/".$image;
			if(file_exists($file_path)){
				$file_path = base_url()."assets/news_img/".$image;
			}else{
				$file_path = base_url()."assets/news_img/no_photo/no_photo.jpg";
			}	
		}else{
				$file_path = base_url()."assets/news_img/no_photo/no_photo.jpg";
		}
		$this->_data['image'] = $file_path;
		return $nd_row;
		
	}
	
	function _check_dropdown($dd){
		
		if($dd <= -1){
			$this->form_validation->set_message("_check_dropdown", "Vous devez choisir le %s");
			return FALSE;
		}else{
			return TRUE;
		}	
	}

}